<!DOCTYPE html >
<html lang="zh">
<head>
    <title>修改信息</title>
    <{include file="public/header" /}>
    <style>
        .weui-uploader__file > img {
            width: 79px;
            height: 79px;
            max-width: 100%;
            max-height: 100%;
        }

        .upload_box, .com-button, .num, .img-count {
            display: block;
        }

        .category {
            padding: 10px;
        }

        .category > li {
            display: inline-block;
            padding: 5px;
            background: #e1e1e1;
            margin: 5px;
            border-radius: 1px;
        }

        .category > li.active {
            background: #03a9f4;
            color: white;
        }

        .avatar-preview > canvas {
            width: 80px;
            height: 80px;
            text-align: center;
        }
    </style>
    <link rel="stylesheet" href="/static/com/jquery-cropper/cropper.css">
</head>
<body ontouchstart>
<!--主体-->
<header class="wy-header">
    <div class="wy-header-icon-back"><span></span></div>
    <div class="wy-header-title">修改信息</div>
</header>
<div class="weui-content clear">

    <div class="weui-cells weui-cells_form">

        <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label  ">昵称修改：</label></div>
            <div class="weui-cell__bd">
                <input autocomplete="off" class="weui-input" name="nickname" type="text" maxlength="32"
                       placeholder="请输入新昵称">

            </div>

        </div>

        <div class="weui-cell">
            <div class="weui-cell__bd">
                <div class="weui-uploader">
                    <div class="weui-uploader__hd">
                        <p class="weui-uploader__title font-14">上传新头像（注意背景，<span style="color: red">大小不超过200kb</span>）
                        </p>
                    </div>
                    <div class="weui-uploader__bd">
                        <ul class="weui-uploader__files" id="uploaderFiles">
                            <li class="weui-uploader__file" style="background-color: #FF5722;">
                                <img id="imag1e" class="comment-img user-avatar"
                                     src="/static/mall/images/user-default.png" alt="">
                            </li>

                        </ul>
                        <div class="weui-uploader__input-box upload_box">
                            <input id="uploaderInput" class="weui-uploader__input" type="file" accept="image/*"
                                   multiple="">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <img id="preview-img" style="max-width: 100%" class="comment-img " src="" alt="">
    <div class="com-button"><a href="javascript:sub();">提交保存</a></div>
</div>

<{include file="public/footer" /}>
<script type="text/javascript" src="/static/mall/js/jquery.Spinner.js"></script>
<!--裁剪-->

<script type="text/javascript" src="/static/com/jquery-cropper/cropper.min.js"></script>
<script type="text/javascript" src="/static/com/jquery-cropper/jquery-cropper.min.js"></script>
<script>
    let blobFile = null;
    let cropper = null;

    $(document).ready(function () {
        $('#uploaderInput').change(function () {

            var file = $(this)[0].files[0]; // 获取用户选择的文件

            var reader = new FileReader(); // 创建FileReader对象
            reader.onload = function () {

                var imgUrl = reader.result; // 读取文件内容并将其转换为图片URL地址
                // 将图片URL地址赋值给img元素的src属性，从而显示预览图

                $('#preview-img').attr('src', imgUrl);
                start_cropper($('#preview-img'),imgUrl)
            };
            reader.readAsDataURL(file); // 以DataURL格式读取文件内容
        });
    });




    function start_cropper($image,newSrc){
        if (cropper){
            $image.cropper('replace',newSrc,true)
            $image.cropper('reset')
        }else{
            showCropper($image);
        }
    }
    function showCropper($image) {
        //var $image = $('#image');
        $image.cropper({
            aspectRatio: 80 / 80,//裁剪比例
            viewMode: 0,
            modal: true,
            autoCrop: true,//自动显示裁剪框
            autoCropArea: 0.3,
            movable: true,//实付可以移动后面的图片
            dragMode: 'crop',//crop/move/none
            //下面的似乎没有作用
            minContainerHeight:30,
            minCropBoxHeight:30,
            minCropBoxWidth:30,
            minCanvasWidth:30,
            minCanvasHeight:30,
            maxCanvasWidth:50,
            maxCanvasHeight:50,
            crop: function (event) {
                previewImg($image);
            },
            ready: function (e) {
                // console.log("ready",e);
                // previewImg();
            },
            cropstart: function (e) {
                //console.log('start',e)
                // previewImg();
            },
            cropmove: function (e) {
                //console.log('move',e)
                // previewImg();
            },
            cropend: function (e) {
                // console.log('end',e)
                // previewImg();
            },
            zoom: function (e) {
                //console.log("zoom",e);
                //previewImg();
            },
        });
        // Get the Cropper.js instance after initialized
        cropper = $image.data('cropper');
    }


    function previewImg(container) {
        var cas = container.cropper('getCroppedCanvas');
        var base64url = cas.toDataURL('image/jpeg');
        cas.toBlob(function (e) {
            blobFile = e
            // console.log('blob', e);  //生成Blob的图片格式
        })
        $(".user-avatar").attr('src', base64url)
    }
</script>
<script>

    $(function () {
        bs_request("<{:url('/mall/user/info')}>", {}, function (res) {
            if (res.code == 0) {
                $(".user-avatar").attr('src', res.data.user_info.avatar);
                $("input[name='nickname']").val(res.data.user_info.nickname);
            }
        });
    })

    function sub() {
        $.confirm('确定提交修改吗？', function () {
            let avatar = $(".user-avatar").attr('src');
            let nickname = $("input[name='nickname']").val().trim();
            if (blobFile) {
                const formData = new FormData();
                // 将Blob格式的数据添加到FormData对象中
                formData.append('file', blobFile, 'image.png');
                $.ajax({
                    url: "<{:url('/mall/com/uploader')}>?from=avatar",
                    type: 'POST',
                    async: false,
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function (res) {
                        res = JSON.parse(res)
                        if (res.code!=0){
                            return $.alert(res.msg)
                        }
                        blobFile = null;
                        $(".user-avatar").attr('src', res.data.url)
                        avatar = res.data.url;
                    },
                    error: function (xhr, status, error) {
                        console.log(error);
                    }
                });
            }

            bs_request("<{:url('update')}>", {avatar: avatar, nickname: nickname}, function (res) {
                $.toast(res.msg, res.code == 0 ? '' : 'cancel', function () {
                    if (res.code == 0) {
                        history.back()
                    }
                })
            })
        })

    }
</script>
</body>
</html>
